package others;

import java.util.concurrent.TimeUnit;

/**
 * 面试题目
 *  银行账户写方法加锁
 *  读方法不加锁行不行
 */
public class Account {
    private String name;
    private double money;

    public synchronized void set(String name, double money) {
        this.name = name;
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.money = money;
    }

    /*方法上加synchronized是对整个对象加锁，所有方法访问前，都会先判断有没有获取到这个对象的锁，这样效率会下降100倍，不建议这样做*/
    public synchronized double getBalance() {
        System.out.println(this.money);
        return this.money;
    }

    public void setBalance(double money) {
        this.money = money;
    }

    public static void main(String[] args) {
        Account account = new Account();
        new Thread(()->account.set("张三", 100.00)).start();
        new Thread(account::getBalance).start();
    }
}
